import React, { useState, useEffect, useRef } from 'react';
import { Layout, Menu, Button, Table, Tag, Space, Modal, Form, Input, Select, message, Switch, InputNumber, Tooltip } from 'antd';
import {
  MenuUnfoldOutlined,
  MenuFoldOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  PlayCircleOutlined,
  StopOutlined,
  LogoutOutlined,
  AppstoreOutlined,
  SettingOutlined,
  DashboardOutlined,
  UserOutlined,
  TeamOutlined,
  FileTextOutlined,
  CheckCircleOutlined,
  ReloadOutlined,
  SyncOutlined,
  GlobalOutlined,
  WifiOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons';
import { useAuth } from '../../contexts/AuthContext';
import './index.css';
import { getUserBrowserNum, getUserInfo, getBrowserList, addBrowser, editBrowser, deleteBrowser, BrowserConfigApi } from '../../utils/request';

const { Header, Sider, Content } = Layout;
const { Option } = Select;

// 定义浏览器配置类型 - 更新以匹配原有功能
interface ProxyConfig {
  enabled: boolean;
  host: string;
  port: number;
  username?: string;
  password?: string;
  type: 'http' | 'https' | 'socks4' | 'socks5';
}

interface BrowserConfig {
  id: string;
  name: string;
  userAgent?: string;
  proxy?: ProxyConfig;
  googleAuto?: boolean; // 新增：Google自动化开关
  googleDomain?: string; // 新增：Google域名
  googleKeyword?: string; // 新增：Google关键词
  googleAutoLaunch?: boolean; // 新增：Google自动启动开关
}

// 浏览器状态接口
interface BrowserStatus {
  isRunning: boolean;
  lastChecked: number;
  inProgress: boolean;
  action?: 'starting' | 'stopping';
}

// 状态显示组件
function StatusDisplay({ status }: { status: BrowserStatus | null }) {
  if (!status) return null;
  
  const timeSinceLastCheck = Date.now() - status.lastChecked;
  const isStale = timeSinceLastCheck > 10000; // 如果超过10秒没有更新，认为状态可能已过期
  
  const getStatusText = () => {
    // 只有在运行中且状态过期时才显示"状态未知"
    if (isStale && status.isRunning) return '状态未知';
    if (status.inProgress) {
      return status.action === 'starting' ? '启动中...' : '停止中...';
    }
    return status.isRunning ? '运行中' : '已停止';
  };

  const getStatusColor = () => {
    // 只有在运行中且状态过期时才显示灰色
    if (isStale && status.isRunning) return '#757575';
    if (status.inProgress) return '#fb8c00';
    return status.isRunning ? '#2e7d32' : '#c62828';
  };
  
  return (
    <div style={{ 
      marginTop: '10px',
      fontSize: '14px'
    }}>
      <strong>状态：</strong>
      <span style={{ 
        color: getStatusColor(),
        display: 'inline-flex',
        alignItems: 'center',
        gap: '4px'
      }}>
        {getStatusText()}
        {isStale && status.isRunning && (
          <span style={{ 
            fontSize: '12px',
            color: '#757575' 
          }}>
            ({Math.floor(timeSinceLastCheck / 1000)}秒前更新)
          </span>
        )}
      </span>
    </div>
  );
}

const MainPage: React.FC = () => {
  const [collapsed, setCollapsed] = useState(false);
  const [browsers, setBrowsers] = useState<BrowserConfig[]>([]);
  const [instanceStatuses, setInstanceStatuses] = useState<Map<string, BrowserStatus>>(new Map());
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [currentBrowser, setCurrentBrowser] = useState<BrowserConfig | null>(null);
  const [selectedMenuKey, setSelectedMenuKey] = useState('2'); // 当前选中的菜单项
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [actionInProgress, setActionInProgress] = useState<string | null>(null);
  const [userAgentValue, setUserAgentValue] = useState<string>(''); // 新增：管理用户代理值

  const [proxyTestLoading, setProxyTestLoading] = useState<boolean>(false);
  const [proxyAuthStatuses, setProxyAuthStatuses] = useState<Map<string, { authenticated: boolean; message: string }>>(new Map());
  const [proxyTestLoadingStates, setProxyTestLoadingStates] = useState<Map<string, boolean>>(new Map());
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
  const [batchUrl, setBatchUrl] = useState<string>('');
  const [batchLoading, setBatchLoading] = useState<boolean>(false);
  const [batchProxyTestLoading, setBatchProxyTestLoading] = useState<boolean>(false);
  const [batchDeleteLoading, setBatchDeleteLoading] = useState<boolean>(false);
  const [batchStopLoading, setBatchStopLoading] = useState<boolean>(false);
  const isInitializedRef = useRef<boolean>(false); // 使用 useRef 防止重复初始化
  const isUserExpireInitializedRef = useRef<boolean>(false); // 用户过期检查的初始化标志
  const userExpireTimerRef = useRef<NodeJS.Timeout | null>(null); // 用户过期检查定时器引用
  const [form] = Form.useForm();
  const { logout, username } = useAuth();

  // 全局用户过期检查函数，不依赖于组件生命周期
  const globalCheckUserExpire = async () => {
    try {
      console.log('=== 全局检查用户信息过期 ===', new Date().toISOString());
      const userInfo = await getUserInfo();
      if (userInfo && userInfo.expire_time) {
        const expireTime = new Date(userInfo.expire_time.replace(/-/g, '/')).getTime();
        const now = Date.now();
        if (expireTime <= now) {
          message.error('账号已过期，请重新登录');
          logout();
          setTimeout(() => {
            window.location.reload();
          }, 1000);
          return;
        }
      }
    } catch (e) {
      console.error('检查用户信息失败', e);
    }
    
    // 设置下次检查
    console.log('设置下次全局用户过期检查定时器，10秒后执行');
    userExpireTimerRef.current = setTimeout(globalCheckUserExpire, 10000);
  };

  // 获取 IPC 渲染器
  const { ipcRenderer } = window.require('electron');

  // 显示错误信息
  const showError = (message: string) => {
    setError(message);
    setTimeout(() => setError(null), 3000);
  };

  // 立即设置 API token（用于已登录用户）
  const setupApiToken = async () => {
    try {
      const token = localStorage.getItem('token');
      if (token) {
        await ipcRenderer.invoke('set-api-token', token);
        console.log('API token 已设置到后端');
      }
    } catch (error) {
      console.warn('设置 API token 失败:', error);
    }
  };

  // 加载配置
  const loadConfigs = async () => {
    try {
      setLoading(true);
      console.log('=== 开始加载浏览器配置 ===', new Date().toISOString());
      const browserList = await getBrowserList();
      console.log('Browser list from API:', browserList);
      
      // 将API数据转换为本地格式
      const configs: BrowserConfig[] = browserList.map(item => {
        try {
          const browserConfig = JSON.parse(item.browser_config);
          return {
            id: item.instance_id,
            name: browserConfig.name || '未命名浏览器',
            userAgent: browserConfig.userAgent,
            proxy: browserConfig.proxy,
            googleAuto: browserConfig.googleAuto, // 加载Google自动化配置
            googleDomain: browserConfig.googleDomain,
            googleKeyword: browserConfig.googleKeyword,
            googleAutoLaunch: browserConfig.googleAutoLaunch
          };
        } catch (error) {
          console.error('解析浏览器配置失败:', error);
          return {
            id: item.instance_id,
            name: '配置解析失败',
            userAgent: '',
            proxy: { enabled: false, host: '', port: 8080, type: 'http' },
            googleAuto: false, // 默认值
            googleDomain: '',
            googleKeyword: '',
            googleAutoLaunch: false
          };
        }
      });
      
      console.log('Converted configs:', configs);
      setBrowsers(configs);
      console.log('=== 配置加载完成 ===');
    } catch (error) {
      showError(error instanceof Error ? error.message : '加载配置失败');
      console.error('Failed to load configs:', error);
    } finally {
      setLoading(false);
    }
  };

  // 更新状态
  const updateStatus = async () => {
    try {
      console.log('正在获取浏览器状态...');
      const statuses = await ipcRenderer.invoke('get-all-browser-statuses');
      if (statuses && typeof statuses === 'object') {
        const statusMap = new Map<string, BrowserStatus>();
        Object.entries(statuses).forEach(([id, status]) => {
          if (status && typeof status === 'object') {
            const typedStatus = status as {
              isRunning?: boolean;
              lastChecked?: number;
              inProgress?: boolean;
              action?: 'starting' | 'stopping';
            };
            
            statusMap.set(id, {
              isRunning: Boolean(typedStatus.isRunning),
              lastChecked: Number(typedStatus.lastChecked) || Date.now(),
              inProgress: Boolean(typedStatus.inProgress),
              action: typedStatus.action
            });
          }
        });
        setInstanceStatuses(statusMap);
      }
    } catch (error) {
      console.error('Failed to update status:', error);
    }
  };

  const updateProxyAuthStatuses = async () => {
    try {
      const statuses = await ipcRenderer.invoke('get-all-proxy-auth-statuses', browsers);
      setProxyAuthStatuses(new Map(Object.entries(statuses)));
    } catch (error) {
      console.error('Failed to update proxy connectivity statuses:', error);
    }
  };

  // 初始化
  useEffect(() => {
    console.log('开始初始化组件...', new Date().toISOString());
    
    const initializeApp = async () => {
      try {
        // 立即设置 API token
        await setupApiToken();
        
        await loadConfigs(); // 加载浏览器配置
        await updateStatus(); // 获取初始状态
        await updateProxyAuthStatuses(); // 获取所有代理连通性状态
      } catch (error) {
        console.error('初始化失败:', error);
      }
    };
    
    initializeApp();
    
    // 监听状态更新事件 - 移除定时器，只依赖事件监听器
    
    // 先移除可能存在的旧监听器
    ipcRenderer.removeAllListeners('browser-status-update');
    
    ipcRenderer.on('browser-status-update', (_, id: string, status: BrowserStatus) => {
      setInstanceStatuses(prev => {
        const newMap = new Map(prev);
        if (status) {
          newMap.set(id, {
            isRunning: Boolean(status.isRunning),
            lastChecked: Number(status.lastChecked) || Date.now(),
            inProgress: Boolean(status.inProgress),
            action: status.action
          });
        } else {
          newMap.delete(id);
        }
        return newMap;
      });
    });
    
    return () => {
      ipcRenderer.removeAllListeners('browser-status-update');
    };
  }, []); // 空依赖数组，只在组件挂载时执行一次

  // 定时检查用户信息是否过期
  useEffect(() => {
    // 防止React.StrictMode导致的重复初始化
    if (isUserExpireInitializedRef.current) {
      console.log('用户过期检查已经初始化过，跳过重复初始化');
      return;
    }
    
    console.log('开始初始化用户过期检查...', new Date().toISOString());
    isUserExpireInitializedRef.current = true;
    
    console.log('用户过期检查初始化完成，开始第一次检查');
    
    // 清理可能存在的旧定时器
    if (userExpireTimerRef.current) {
      clearTimeout(userExpireTimerRef.current);
      userExpireTimerRef.current = null;
    }

    // 立即开始第一次检查
    globalCheckUserExpire();
    
    // 清理函数
    return () => {
      console.log('清理用户过期检查定时器');
      if (userExpireTimerRef.current) {
        clearTimeout(userExpireTimerRef.current);
        userExpireTimerRef.current = null;
      }
    };
  }, []); // 空依赖数组，只在组件挂载时执行一次

  // 在 MainPage 组件内部 state 区域添加 Google 自动化相关状态
  const [googleAutoEnabled, setGoogleAutoEnabled] = useState<boolean>(() => {
    return localStorage.getItem('googleAutoEnabled') === 'true';
  });
  const [googleDomain, setGoogleDomain] = useState<string>(() => {
    return localStorage.getItem('googleDomain') || '';
  });
  const [googleKeyword, setGoogleKeyword] = useState<string>(() => {
    return localStorage.getItem('googleKeyword') || '';
  });
  const [googleAutoLaunch, setGoogleAutoLaunch] = useState<boolean>(() => {
    return localStorage.getItem('googleAutoLaunch') === 'true';
  });

  // 同步localStorage
  useEffect(() => {
    localStorage.setItem('googleAutoEnabled', googleAutoEnabled ? 'true' : 'false');
  }, [googleAutoEnabled]);
  useEffect(() => {
    localStorage.setItem('googleDomain', googleDomain);
  }, [googleDomain]);
  useEffect(() => {
    localStorage.setItem('googleKeyword', googleKeyword);
  }, [googleKeyword]);
  useEffect(() => {
    localStorage.setItem('googleAutoLaunch', googleAutoLaunch ? 'true' : 'false');
  }, [googleAutoLaunch]);

  // 处理新增/编辑浏览器
  const handleModalOpen = (browser?: BrowserConfig) => {
    setIsModalVisible(true);
    if (browser) {
      setCurrentBrowser(browser);
      setUserAgentValue(browser.userAgent || '');
      form.setFieldsValue(browser);
    } else {
      setCurrentBrowser(null);
      setUserAgentValue('');
      form.resetFields();
    }
  };

  const handleModalCancel = () => {
    setIsModalVisible(false);
    setUserAgentValue('');
    form.resetFields();
  };

  const handleFormSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      // 准备浏览器配置对象
      const browserConfig = {
        name: values.name,
        userAgent: values.userAgent,
        proxy: values.proxy || { enabled: false, host: '', port: 8080, type: 'http' },
        id: currentBrowser ? currentBrowser.id : Date.now().toString()
      };
      
      // 转换为字符串
      const browserConfigString = JSON.stringify(browserConfig);
      
      if (currentBrowser) {
        // 编辑现有浏览器
        try {
          await editBrowser(currentBrowser.id, browserConfigString);
          message.success('浏览器配置更新成功');
          await loadConfigs(); // 刷新列表
          await updateProxyAuthStatuses(); // 更新代理连通性状态
        } catch (error) {
          message.error(error instanceof Error ? error.message : '更新配置失败');
          return;
        }
      } else {
        // 创建新浏览器前，先校验数量
        try {
          const browserNum = await getUserBrowserNum();
          if (browsers.length >= browserNum) {
            message.error(`已达到最大浏览器环境数（${browserNum}），无法创建新环境。`);
            return;
          }
        } catch (err) {
          message.error(err instanceof Error ? err.message : '校验浏览器数量失败');
          return;
        }
        
        // 创建新浏览器
        try {
          await addBrowser(browserConfig.id, browserConfigString);
          message.success('新浏览器环境创建成功');
          await loadConfigs(); // 刷新列表
          await updateProxyAuthStatuses(); // 更新代理连通性状态
        } catch (error) {
          message.error(error instanceof Error ? error.message : '创建配置失败');
          return;
        }
      }
      
      setIsModalVisible(false);
    } catch (error) {
      message.error('表单验证失败，请检查输入');
    }
  };

  // 处理删除浏览器
  const handleDelete = async (id: string) => {
    const status = instanceStatuses.get(id);
    if (status?.isRunning || status?.inProgress) {
      message.error('无法删除运行中的浏览器实例');
      return;
    }

    Modal.confirm({
      title: '确认删除',
      content: '确定要删除此浏览器环境吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          setActionInProgress(`deleting-${id}`);
          await deleteBrowser(id);
          message.success('浏览器环境已删除');
          await loadConfigs(); // 刷新列表
        } catch (error) {
          message.error(error instanceof Error ? error.message : '删除配置失败');
        } finally {
          setActionInProgress(null);
        }
      }
    });
  };

  // 修改 handleLaunch 方法，支持Google自动化参数
  const handleLaunch = async (config: BrowserConfig) => {
    try {
      setActionInProgress(`launching-${config.id}`);
      // 传递Google自动化参数
      const launchParams = { ...config };
      if (googleAutoEnabled && googleDomain && googleKeyword) {
        launchParams.googleAuto = true;
        launchParams.googleDomain = googleDomain;
        launchParams.googleKeyword = googleKeyword;
      }
      const result = await ipcRenderer.invoke('launch-browser', launchParams);
      if (!result.success) {
        showError(result.error || '启动浏览器失败');
      }
      // 状态更新通过事件监听器自动处理，不需要手动调用 updateStatus
    } catch (error) {
      showError(error instanceof Error ? error.message : '启动浏览器失败');
    } finally {
      setActionInProgress(null);
    }
  };

  const handleStop = async (id: string) => {
    try {
      setActionInProgress(`stopping-${id}`);
      const result = await ipcRenderer.invoke('stop-browser', id);
      if (!result.success) {
        showError(result.error || '停止浏览器失败');
      }
      // 状态更新通过事件监听器自动处理，不需要手动调用 updateStatus
    } catch (error) {
      showError(error instanceof Error ? error.message : '停止浏览器失败');
    } finally {
      setActionInProgress(null);
    }
  };

  // 生成用户代理
  const handleGenerateUserAgent = async () => {
    try {
      console.log('开始生成用户代理...');
      const result = await ipcRenderer.invoke('generate-user-agent');
      console.log('IPC 返回结果:', result);
      
      if (result) {
        console.log('设置用户代理值:', result);
        setUserAgentValue(result); // 直接设置状态
        form.setFieldsValue({ userAgent: result }); // 同时设置表单值
        message.success('用户代理生成成功');
      } else {
        console.error('IPC 返回空结果');
        showError('生成User Agent失败：返回结果为空');
      }
    } catch (error) {
      console.error('生成用户代理错误:', error);
      showError('生成User Agent失败');
    }
  };

  // 处理菜单点击
  const handleMenuClick = ({ key }: { key: string }) => {
    setSelectedMenuKey(key);
    // message.info(`切换到${getMenuTitle(key)}`);
  };

  // 获取菜单标题
  const getMenuTitle = (key: string) => {
    const menuMap: { [key: string]: string } = {
      '1': '仪表盘',
      '2': '浏览器环境管理',
      '3': '用户管理',
      '4': '日志记录',
      '5': '系统设置'
    };
    return menuMap[key] || '未知页面';
  };

  // 同步相关函数
  // 刷新浏览器列表
  const handleRefreshList = async () => {
    try {
      setLoading(true);
      await loadConfigs();
      await updateProxyAuthStatuses();
      message.success('浏览器列表已刷新');
    } catch (error) {
      message.error('刷新失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const handleTestProxy = async (config: BrowserConfig) => {
    try {
      // 设置当前配置的loading状态
      setProxyTestLoadingStates(prev => {
        const newMap = new Map(prev);
        newMap.set(config.id, true);
        return newMap;
      });
      
      // 如果是从列表调用，直接使用配置中的代理信息
      // 如果是从表单调用，获取表单的代理配置
      let proxyConfig;
      if (config.proxy) {
        proxyConfig = config.proxy;
      } else {
        const formValues = await form.validateFields();
        proxyConfig = formValues.proxy;
      }
      
      if (!proxyConfig || !proxyConfig.enabled) {
        message.error('请先启用并配置代理');
        return;
      }

      // 验证代理配置的必填字段
      if (!proxyConfig.host || !proxyConfig.port || !proxyConfig.type) {
        message.error('请填写完整的代理配置信息');
        return;
      }

      // 构建临时配置用于测试
      const testConfig: BrowserConfig = {
        id: config.id,
        name: config.name,
        proxy: proxyConfig
      };

      console.log('Testing proxy config:', testConfig);

      const result = await ipcRenderer.invoke('test-proxy', testConfig);
      
      if (result.success) {
        message.success(result.message);
        // 测试成功后更新连通性状态
        const authStatus = await ipcRenderer.invoke('get-proxy-auth-status', testConfig);
        setProxyAuthStatuses(prev => {
          const newMap = new Map(prev);
          newMap.set(config.id, authStatus);
          return newMap;
        });
      } else {
        message.error(result.message);
        // 测试失败时也更新状态
        setProxyAuthStatuses(prev => {
          const newMap = new Map(prev);
          newMap.set(config.id, { authenticated: false, message: result.message });
          return newMap;
        });
      }
    } catch (error) {
      console.error('Proxy test failed:', error);
      if (error instanceof Error && error.message.includes('validation')) {
        message.error('请检查代理配置信息是否完整');
      } else {
        message.error('代理测试失败');
      }
    } finally {
      // 清除当前配置的loading状态
      setProxyTestLoadingStates(prev => {
        const newMap = new Map(prev);
        newMap.set(config.id, false);
        return newMap;
      });
    }
  };

  // 专门处理表单中的代理测试
  const handleFormProxyTest = async () => {
    try {
      setProxyTestLoading(true);
      
      // 获取表单的代理配置
      const formValues = await form.validateFields();
      const proxyConfig = formValues.proxy;
      
      if (!proxyConfig || !proxyConfig.enabled) {
        message.error('请先启用并配置代理');
        return;
      }

      // 验证代理配置的必填字段
      if (!proxyConfig.host || !proxyConfig.port || !proxyConfig.type) {
        message.error('请填写完整的代理配置信息');
        return;
      }

      // 构建临时配置用于测试
      const testConfig: BrowserConfig = {
        id: currentBrowser?.id || 'temp-test',
        name: currentBrowser?.name || formValues.name || '临时测试',
        proxy: proxyConfig
      };

      console.log('Testing form proxy config:', testConfig);

      const result = await ipcRenderer.invoke('test-proxy', testConfig);
      
      if (result.success) {
        message.success(result.message);
      } else {
        message.error(result.message);
      }
    } catch (error) {
      console.error('Form proxy test failed:', error);
      if (error instanceof Error && error.message.includes('validation')) {
        message.error('请检查代理配置信息是否完整');
      } else {
        message.error('代理测试失败');
      }
    } finally {
      setProxyTestLoading(false);
    }
  };

  // 验证域名格式
  const validateDomain = (url: string): boolean => {
    // 支持带路径的URL正则表达式
    const urlRegex = /^(https?:\/\/)?([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}(\/.*)?$/;
    return urlRegex.test(url);
  };

  // 批量打开浏览器
  const handleBatchLaunch = async () => {
    // 立即验证域名格式
    if (!batchUrl.trim()) {
      message.error('请输入要访问的域名');
      return;
    }

    if (!validateDomain(batchUrl)) {
      message.error('请输入有效的域名或URL格式（如：www.google.com 或 https://myip.ipip.net/）');
      return;
    }

    if (selectedRowKeys.length === 0) {
      message.error('请先选择要打开的浏览器');
      return;
    }

    try {
      setBatchLoading(true);
      const selectedConfigs = browsers.filter(browser => selectedRowKeys.includes(browser.id));
      
      for (const config of selectedConfigs) {
        try {
          const result = await ipcRenderer.invoke('launch-browser', config);
          if (result.success) {
            // 立即导航到指定域名
            const fullUrl = batchUrl.startsWith('http://') || batchUrl.startsWith('https://') ? batchUrl : `https://${batchUrl}`;
            await ipcRenderer.invoke('navigate-browser', config.id, fullUrl);
          }
        } catch (error) {
          console.error(`Failed to launch browser ${config.name}:`, error);
        }
      }
      
      message.success(`已启动 ${selectedConfigs.length} 个浏览器实例`);
      await updateStatus();
    } catch (error) {
      message.error('批量启动失败');
    } finally {
      setBatchLoading(false);
    }
  };

  // 批量检测代理
  const handleBatchProxyTest = async () => {
    if (selectedRowKeys.length === 0) {
      message.error('请先选择要检测的浏览器');
      return;
    }

    try {
      setBatchProxyTestLoading(true);
      const selectedConfigs = browsers.filter(browser => selectedRowKeys.includes(browser.id));
      const configsWithProxy = selectedConfigs.filter(config => config.proxy && config.proxy.enabled);
      
      if (configsWithProxy.length === 0) {
        message.info('选中的浏览器都没有配置代理，跳过检测');
        return;
      }

      for (const config of configsWithProxy) {
        try {
          await handleTestProxy(config);
          // 等待一小段时间再检测下一个
          await new Promise(resolve => setTimeout(resolve, 500));
        } catch (error) {
          console.error(`Failed to test proxy for ${config.name}:`, error);
        }
      }
      
      message.success(`已检测 ${configsWithProxy.length} 个代理配置`);
    } catch (error) {
      message.error('批量检测失败');
    } finally {
      setBatchProxyTestLoading(false);
    }
  };

  // 批量删除浏览器
  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      message.error('请先选择要删除的浏览器');
      return;
    }

    // 检查是否有运行中的浏览器
    const selectedConfigs = browsers.filter(browser => selectedRowKeys.includes(browser.id));
    const runningConfigs = selectedConfigs.filter(config => {
      const status = instanceStatuses.get(config.id);
      return status?.isRunning || status?.inProgress;
    });

    if (runningConfigs.length > 0) {
      message.error(`无法删除运行中的浏览器实例: ${runningConfigs.map(c => c.name).join(', ')}`);
      return;
    }

    Modal.confirm({
      title: '确认批量删除',
      content: `确定要删除选中的 ${selectedRowKeys.length} 个浏览器环境吗？此操作不可恢复。`,
      okText: '确认删除',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        try {
          setBatchDeleteLoading(true);
          let successCount = 0;
          let failCount = 0;

          for (const id of selectedRowKeys) {
            try {
              await deleteBrowser(id);
              successCount++;
            } catch (error) {
              console.error(`Failed to delete browser ${id}:`, error);
              failCount++;
            }
          }

          await loadConfigs(); // 刷新列表
          setSelectedRowKeys([]); // 清空选择

          if (failCount === 0) {
            message.success(`成功删除 ${successCount} 个浏览器环境`);
          } else {
            message.warning(`删除完成：成功 ${successCount} 个，失败 ${failCount} 个`);
          }
        } catch (error) {
          message.error('批量删除失败');
        } finally {
          setBatchDeleteLoading(false);
        }
      }
    });
  };

  // 批量关闭浏览器
  const handleBatchStop = async () => {
    if (selectedRowKeys.length === 0) {
      message.error('请先选择要关闭的浏览器');
      return;
    }

    // 检查是否有运行中的浏览器
    const selectedConfigs = browsers.filter(browser => selectedRowKeys.includes(browser.id));
    const runningConfigs = selectedConfigs.filter(config => {
      const status = instanceStatuses.get(config.id);
      return status?.isRunning;
    });

    if (runningConfigs.length === 0) {
      message.info('选中的浏览器都没有在运行，无需关闭');
      return;
    }

    Modal.confirm({
      title: '确认批量关闭',
      content: `确定要关闭选中的 ${runningConfigs.length} 个运行中的浏览器实例吗？`,
      okText: '确认关闭',
      cancelText: '取消',
      onOk: async () => {
        try {
          setBatchStopLoading(true);
          let successCount = 0;
          let failCount = 0;

          for (const config of runningConfigs) {
            try {
              const result = await ipcRenderer.invoke('stop-browser', config.id);
              if (result.success) {
                successCount++;
              } else {
                failCount++;
              }
            } catch (error) {
              console.error(`Failed to stop browser ${config.name}:`, error);
              failCount++;
            }
          }

          await updateStatus();

          if (failCount === 0) {
            message.success(`成功关闭 ${successCount} 个浏览器实例`);
          } else {
            message.warning(`关闭完成：成功 ${successCount} 个，失败 ${failCount} 个`);
          }
        } catch (error) {
          message.error('批量关闭失败');
        } finally {
          setBatchStopLoading(false);
        }
      }
    });
  };

  // 渲染不同页面的内容
  const renderContent = () => {
    if (loading) {
      return (
        <div style={{ textAlign: 'center', padding: '40px' }}>
          加载中...
        </div>
      );
    }

    switch (selectedMenuKey) {
      case '1':
        return (
          <div style={{ textAlign: 'center', padding: '40px' }}>
            <h2>仪表盘</h2>
            <p>欢迎使用YinianDa Fingerprint Browser</p>
            <div style={{ display: 'flex', justifyContent: 'space-around', marginTop: '40px' }}>
              <div style={{ textAlign: 'center' }}>
                <h3>{browsers.length}</h3>
                <p>总环境数</p>
              </div>
              <div style={{ textAlign: 'center' }}>
                <h3>{Array.from(instanceStatuses.values()).filter(s => s.isRunning).length}</h3>
                <p>运行中</p>
              </div>
              <div style={{ textAlign: 'center' }}>
                <h3>{Array.from(instanceStatuses.values()).filter(s => !s.isRunning).length}</h3>
                <p>已停止</p>
              </div>
            </div>
          </div>
        );
      case '2':
        return (
          <div>
            {/* 批量操作区域 */}
            <div style={{ 
              marginBottom: 16, 
              padding: '16px', 
              backgroundColor: '#f5f5f5', 
              borderRadius: '6px',
              border: '1px solid #d9d9d9'
            }}>
              <div style={{ marginBottom: '12px', fontWeight: 'bold', color: '#333' }}>
                批量操作
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: '12px', flexWrap: 'wrap' }}>
                <Input
                  placeholder="请输入域名或URL（如：www.google.com 或 https://myip.ipip.net/）"
                  value={batchUrl}
                  onChange={(e) => setBatchUrl(e.target.value)}
                  style={{ width: '300px' }}
                />
                <Button
                  type="primary"
                  icon={<PlayCircleOutlined />}
                  onClick={handleBatchLaunch}
                  loading={batchLoading}
                  disabled={selectedRowKeys.length === 0 || !batchUrl.trim() || !validateDomain(batchUrl)}
                  style={{ 
                    backgroundColor: (selectedRowKeys.length === 0 || !batchUrl.trim() || !validateDomain(batchUrl)) ? '#8cc8ff' : '#1890ff', 
                    borderColor: (selectedRowKeys.length === 0 || !batchUrl.trim() || !validateDomain(batchUrl)) ? '#8cc8ff' : '#1890ff', 
                    color: 'white' 
                  }}
                >
                  批量打开 ({selectedRowKeys.length})
                </Button>
                <Button
                  icon={<SyncOutlined />}
                  onClick={handleBatchProxyTest}
                  loading={batchProxyTestLoading}
                  disabled={selectedRowKeys.length === 0}
                  style={{ 
                    backgroundColor: selectedRowKeys.length === 0 ? '#a8e6a8' : '#52c41a', 
                    borderColor: selectedRowKeys.length === 0 ? '#a8e6a8' : '#52c41a', 
                    color: 'white' 
                  }}
                >
                  批量代理检测
                </Button>
                <Button
                  danger
                  icon={<DeleteOutlined />}
                  onClick={handleBatchDelete}
                  loading={batchDeleteLoading}
                  disabled={selectedRowKeys.length === 0}
                  style={{ 
                    backgroundColor: selectedRowKeys.length === 0 ? '#ffb3b3' : '#ff4d4f', 
                    borderColor: selectedRowKeys.length === 0 ? '#ffb3b3' : '#ff4d4f', 
                    color: 'white' 
                  }}
                >
                  批量删除 ({selectedRowKeys.length})
                </Button>
                <Button
                  icon={<StopOutlined />}
                  onClick={handleBatchStop}
                  loading={batchStopLoading}
                  disabled={selectedRowKeys.length === 0}
                  style={{ 
                    backgroundColor: selectedRowKeys.length === 0 ? '#ffd591' : '#fa8c16', 
                    borderColor: selectedRowKeys.length === 0 ? '#ffd591' : '#fa8c16', 
                    color: 'white' 
                  }}
                >
                  批量关闭
                </Button>
              </div>
            </div>

            {/* Google自动化开关及配置 */}
            <div style={{
              marginBottom: 16,
              padding: '16px',
              backgroundColor: '#f0f7ff',
              borderRadius: '6px',
              border: '1px solid #91d5ff'
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <span style={{ fontWeight: 'bold', color: '#1890ff' }}>Google自动化</span>
                <Switch
                  checked={googleAutoEnabled}
                  onChange={setGoogleAutoEnabled}
                  checkedChildren="启用"
                  unCheckedChildren="关闭"
                />
                {googleAutoEnabled && (
                  <>
                    <Input
                      placeholder="请输入目标域名（如：www.example.com）"
                      value={googleDomain}
                      onChange={e => setGoogleDomain(e.target.value)}
                      style={{ width: 220 }}
                    />
                    <Input
                      placeholder="请输入搜索关键词"
                      value={googleKeyword}
                      onChange={e => setGoogleKeyword(e.target.value)}
                      style={{ width: 220 }}
                    />
                    <span>自动启动时执行</span>
                    <Switch
                      checked={googleAutoLaunch}
                      onChange={setGoogleAutoLaunch}
                      checkedChildren="是"
                      unCheckedChildren="否"
                    />
                  </>
                )}
              </div>
            </div>

            <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => handleModalOpen()}
              >
                新增浏览器环境
              </Button>
              
              {/* 刷新按钮 */}
              <Tooltip title="刷新浏览器列表">
                <Button
                  icon={<ReloadOutlined />}
                  onClick={handleRefreshList}
                  loading={loading}
                  style={{ marginLeft: 8 }}
                >
                  刷新列表
                </Button>
              </Tooltip>
              
              {/* 调试按钮 - 检查 Token 状态 */}
  
            </div>

            {error && (
              <div style={{ 
                marginBottom: 16, 
                padding: '8px 12px', 
                backgroundColor: '#fff2f0', 
                border: '1px solid #ffccc7',
                borderRadius: '6px',
                color: '#cf1322'
              }}>
                {error}
              </div>
            )}

            <Table
              columns={columns}
              dataSource={browsers}
              rowKey="id"
              pagination={{ pageSize: 10 }}
              rowSelection={{
                selectedRowKeys,
                onChange: (selectedKeys) => setSelectedRowKeys(selectedKeys as string[]),
              }}
            />
          </div>
        );
      case '3':
        return (
          <div style={{ textAlign: 'center', padding: '40px' }}>
            <h2>用户管理</h2>
            <p>用户管理功能开发中...</p>
          </div>
        );
      case '4':
        return (
          <div style={{ textAlign: 'center', padding: '40px' }}>
            <h2>日志记录</h2>
            <p>日志记录功能开发中...</p>
          </div>
        );
      case '5':
        return (
          <div style={{ textAlign: 'center', padding: '40px' }}>
            <h2>系统设置</h2>
            <p>系统设置功能开发中...</p>
          </div>
        );
      default:
        return <div>页面不存在</div>;
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      width: 150,
    },
    {
      title: '状态',
      key: 'status',
      width: 150,
      render: (_: any, record: BrowserConfig) => {
        const status = instanceStatuses.get(record.id);
        return <StatusDisplay status={status || null} />;
      },
    },
    {
      title: '浏览器UA',
      dataIndex: 'userAgent',
      key: 'userAgent',
      render: (ua: string) => ua || '默认UA',
    },
    {
      title: '代理设置',
      key: 'proxy',
      width: 150,
      render: (_: any, record: BrowserConfig) => {
        if (!record.proxy || !record.proxy.enabled) {
          return <Tag color="default">未配置</Tag>;
        }
        
        const proxyType = record.proxy.type.toUpperCase();
        const proxyHost = record.proxy.host;
        const proxyPort = record.proxy.port;
        
        // 获取代理连通性状态
        const authStatus = proxyAuthStatuses.get(record.id);
        
        return (
          <div>
            <Tag color="blue">{proxyType}</Tag>
            <div style={{ fontSize: '12px', color: '#666', marginTop: '4px' }}>
              {proxyHost}:{proxyPort}
              {authStatus && (
                <Tag 
                  color={authStatus.authenticated ? 'green' : 'red'} 
                  style={{ fontSize: '10px', marginLeft: '4px' }}
                >
                  {authStatus.authenticated ? '已生效' : '未生效'}
                </Tag>
              )}
            </div>
            <Button 
              type="link" 
              size="small" 
              style={{ padding: 0, fontSize: '12px' }}
              onClick={() => handleTestProxy(record)}
              loading={proxyTestLoadingStates.get(record.id) || false}
            >
              测试连通性
            </Button>
          </div>
        );
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 250,
      render: (_: any, record: BrowserConfig) => {
        const status = instanceStatuses.get(record.id);
        const isRunning = status?.isRunning;
        const inProgress = status?.inProgress;
        const isDeleting = actionInProgress === `deleting-${record.id}`;
        const isLaunching = actionInProgress === `launching-${record.id}`;
        const isStopping = actionInProgress === `stopping-${record.id}`;

        return (
          <Space size="small">
            <Button
              icon={<EditOutlined />}
              size="small"
              onClick={() => handleModalOpen(record)}
              disabled={inProgress}
            >
              编辑
            </Button>
            {isRunning ? (
              <Button
                icon={<StopOutlined />}
                size="small"
                danger
                loading={isStopping}
                onClick={() => handleStop(record.id)}
                disabled={inProgress}
              >
                {isStopping ? '停止中...' : '停止'}
              </Button>
            ) : (
              <Button
                icon={<PlayCircleOutlined />}
                size="small"
                type="primary"
                loading={isLaunching}
                onClick={() => handleLaunch(record)}
                disabled={inProgress}
              >
                {isLaunching ? '启动中...' : '启动'}
              </Button>
            )}
            <Button
              icon={<DeleteOutlined />}
              size="small"
              danger
              loading={isDeleting}
              onClick={() => handleDelete(record.id)}
              disabled={isRunning || inProgress}
            >
              {isDeleting ? '删除中...' : '删除'}
            </Button>
          </Space>
        );
      },
    },
  ];

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Sider trigger={null} collapsible collapsed={collapsed} width={250} className="sidebar">
        <div className="sidebar-header">
          <h1 className="sidebar-title">YinianDa Fingerprint Browser</h1>
          <Button
            type="text"
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={() => setCollapsed(!collapsed)}
            className="sidebar-toggle"
          />
        </div>
        <Menu 
          theme="light" 
          mode="inline" 
          selectedKeys={[selectedMenuKey]} 
          className="sidebar-menu" 
          onClick={handleMenuClick}
        >
   
          <Menu.Item key="2" icon={<AppstoreOutlined />} className="sidebar-menu-item">
            浏览器环境管理
          </Menu.Item>

        </Menu>
        <div className="sidebar-footer">
          <Button
            type="text"
            icon={<LogoutOutlined />}
            onClick={logout}
            className="sidebar-logout"
          >
            退出登录
          </Button>
        </div>
      </Sider>
      <Layout className="site-layout">
        <Header style={{ padding: '0 16px', background: '#fff', boxShadow: '0 1px 4px rgba(0,0,0,0.1)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', height: '100%' }}>
            <h2 style={{ margin: 0, fontSize: 18 }}>{getMenuTitle(selectedMenuKey)}</h2>
            {username && (
              <div style={{ 
                display: 'flex', 
                alignItems: 'center', 
                gap: '8px',
                fontSize: '14px',
                color: '#666'
              }}>
                <UserOutlined />
                <span>当前用户：{username}</span>
              </div>
            )}
          </div>
        </Header>
        <Content style={{ margin: '16px', padding: 24, background: '#fff', minHeight: 280 }}>
          {renderContent()}
        </Content>
      </Layout>

      {/* 新增/编辑浏览器模态框 */}
      <Modal
        title={currentBrowser ? '编辑浏览器环境' : '新增浏览器环境'}
        visible={isModalVisible}
        onCancel={handleModalCancel}
        footer={[
          <Button key="cancel" onClick={handleModalCancel}>
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={handleFormSubmit}>
            {currentBrowser ? '更新' : '创建'}
          </Button>,
        ]}
      >
        <Form
          form={form}
          layout="vertical"
          name="browser_form"
          initialValues={{ 
            proxy: {
              enabled: false,
              type: 'http',
              host: '',
              port: 8080,
              username: '',
              password: ''
            }
          }}
        >
          <Form.Item
            name="name"
            label="环境名称"
            rules={[{ required: true, message: '请输入环境名称' }]}
          >
            <Input placeholder="请输入浏览器环境名称" />
          </Form.Item>
  
          <Form.Item
            name="userAgent"
            label="浏览器UA"
          >
            <Input.Group compact>
              <Input 
                value={userAgentValue}
                onChange={(e) => {
                  setUserAgentValue(e.target.value);
                  form.setFieldsValue({ userAgent: e.target.value });
                }}
                placeholder="User Agent（可选）" 
                style={{ width: 'calc(100% - 80px)' }}
              />
              <Button
                onClick={handleGenerateUserAgent}
                style={{ 
                  width: '80px',
                  height: '32px',
                  margin:0,
                  borderTopLeftRadius: 0,
                  borderBottomLeftRadius: 0
                }}
                type="primary"
              >
                生成UA
              </Button>
            </Input.Group>
          </Form.Item>

          {/* 代理配置部分 */}
          <Form.Item
            name={['proxy', 'enabled']}
            label="代理设置"
            valuePropName="checked"
          >
            <Switch checkedChildren="启用" unCheckedChildren="禁用" />
          </Form.Item>

          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => 
              prevValues?.proxy?.enabled !== currentValues?.proxy?.enabled
            }
          >
            {({ getFieldValue }) => {
              const proxyEnabled = getFieldValue(['proxy', 'enabled']);
              
              if (!proxyEnabled) return null;
              
              return (
                <div style={{ 
                  border: '1px solid #d9d9d9', 
                  borderRadius: '6px', 
                  padding: '16px', 
                  marginBottom: '16px',
                  backgroundColor: '#fafafa'
                }}>
                  <Form.Item
                    name={['proxy', 'type']}
                    label="代理类型"
                    rules={[{ required: true, message: '请选择代理类型' }]}
                  >
                    <Select placeholder="选择代理类型">
                      <Option value="http">HTTP</Option>
                      <Option value="https">HTTPS</Option>
                      <Option value="socks4">SOCKS4</Option>
                      <Option value="socks5">SOCKS5</Option>
                    </Select>
                  </Form.Item>

                  <Form.Item
                    name={['proxy', 'host']}
                    label="代理主机"
                    rules={[{ required: true, message: '请输入代理主机地址' }]}
                  >
                    <Input placeholder="例如: 127.0.0.1 或 proxy.example.com" />
                  </Form.Item>

                  <Form.Item
                    name={['proxy', 'port']}
                    label="代理端口"
                    rules={[
                      { required: true, message: '请输入代理端口' },
                      { type: 'number', min: 1, max: 65535, message: '端口号必须在1-65535之间' }
                    ]}
                  >
                    <InputNumber 
                      placeholder="例如: 8080" 
                      style={{ width: '100%' }}
                      min={1}
                      max={65535}
                    />
                  </Form.Item>

                  <Form.Item
                    name={['proxy', 'username']}
                    label="用户名（可选）"
                  >
                    <Input placeholder="代理认证用户名" />
                  </Form.Item>

                  <Form.Item
                    name={['proxy', 'password']}
                    label="密码（可选）"
                  >
                    <Input.Password placeholder="代理认证密码" />
                  </Form.Item>

                  <Form.Item>
                    <Button
                      type="dashed"
                      onClick={handleFormProxyTest}
                      loading={proxyTestLoading}
                      style={{ width: '100%' }}
                    >
                      测试代理连接
                    </Button>
                  </Form.Item>
                </div>
              );
            }}
          </Form.Item>
        </Form>
      </Modal>
    </Layout>
  );
};

export default MainPage;